package com.yonyou.crm.cum.customer.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.base.doc.service.BaseDocDetailBizServiceImpl;
import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.model.util.ModelUtil;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.cum.customer.entity.CustomerSalesDO;
import com.yonyou.crm.cum.customer.entity.CustomerSalesVO;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class CustomerSalesBizServiceImpl extends BaseBizServiceImpl<CustomerSalesDO>{

	@Autowired
	private SysOrgBizServiceImpl orgService;
	
	@Autowired
	private UserBizServiceImpl userService;
	
	@Autowired
	private CustomerOwnerBizServiceImpl ownerService;
	
	@Autowired
	private BaseDocDetailBizServiceImpl baseDocDetailBizService;
	
	@Autowired
	private CustomerBizServiceImpl cumService;
	
	public List<CustomerSalesVO> selectByCustomer(Map<String, Object> param) {
		List<CustomerSalesDO> list = dao.selectVoList(CustomerSalesDO.class, "selectByCustomer", param);
		List<CustomerSalesVO> result = ModelUtil.copyModelList(list, CustomerSalesVO.class);
		transCustomerSale(result);
		return result;
	}
	
	public Page<CustomerSalesVO> getList(Page<CustomerSalesVO> page,Map<String, Object> paramMap){
		Page<CustomerSalesDO> pageList = super.pageSelect(CustomerSalesDO.class,page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		Page<CustomerSalesVO> result = ModelUtil.copyPageModel(pageList, CustomerSalesVO.class); 
		return result;
	}
	
	public CustomerSalesVO getDetail(Long id){
		CustomerSalesDO saleDO = super.getVOById(CustomerSalesDO.class, id);
		CustomerSalesVO saleVO = ModelUtil.copyModel(saleDO, CustomerSalesVO.class);
		return saleVO;
	}
	
	protected void beforeSaveVO(CustomerSalesDO customerSale){
		super.beforeSaveVO(customerSale);
		if (customerSale.getCreatedTime() == null) {
			customerSale.setCreatedTime(new Date());
		}
		if (customerSale.getCreatedUserId() == null) {
			customerSale.setCreatedUserId(Long.valueOf(InvocationInfoProxy.getParameter(LoginContextConstant.UserId)));
		}
	}
	
	public CustomerSalesVO insert(CustomerSalesVO customerSale){
		CustomerSalesDO saleDO = ModelUtil.copyModel(customerSale, CustomerSalesDO.class);
		CustomerSalesVO res = ModelUtil.copyModel(super.saveVO(saleDO), CustomerSalesVO.class);
		return res;
	}
	
	
	public CustomerSalesVO update(CustomerSalesVO customerSale) {
		CustomerSalesDO saleDO = ModelUtil.copyModel(customerSale, CustomerSalesDO.class);
		CustomerSalesDO res = super.updateVO(saleDO);
		CustomerSalesVO saleVO = ModelUtil.copyModel(res, CustomerSalesVO.class);
		transCustomerSale(Arrays.asList(saleVO));
		return saleVO;
	}
	
	
	public int delete(Long cumId){
		Map<String, Object> paraMap = new HashMap<String, Object>();
		
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		paraMap.put("orgId", orgId);
		paraMap.put("tenantId", tenantId);
		paraMap.put("cumId", cumId);
		
		return dao.deleteSql(CustomerSalesDO.class, "deleteByCumId", paraMap);
	}
	
	public int batchDeleteByCumIds(String[] cumIds){
		Map<String, Object> paraMap = new HashMap<String, Object>();
		
		String orgIdStr = (String)InvocationInfoProxy.getParameter("orgid");//所属公司
		String tenantIdStr = (String)InvocationInfoProxy.getTenantid();
		Long orgId = Long.parseLong(orgIdStr);
		Long tenantId = Long.parseLong(tenantIdStr);

		paraMap.put("orgId", orgId);
		paraMap.put("tenantId", tenantId);
		paraMap.put("cumIds", cumIds);
		
		return dao.deleteSql(CustomerSalesDO.class, "batchDeleteByCumIds", paraMap);
	}
	
	public List<CustomerSalesVO> transCustomerSale(List<CustomerSalesVO> customerSaleList) {
		
		List<FieldRelation<CustomerSalesVO>> relations = new ArrayList<FieldRelation<CustomerSalesVO>>();
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "orgId", new String[]{"orgName"}, orgService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "ownerDeptId", new String[]{"ownerDeptName"}, orgService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "ownerUserId", new String[]{"ownerUserName"}, userService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "level", new String[]{"levelName"}, baseDocDetailBizService, "selectFieldsByIds"));
		relations.add(new RefFieldRelation<CustomerSalesVO>(CustomerSalesVO.class, "state", new String[]{"stateName"}, baseDocDetailBizService, "selectFieldsByIds"));
		new FieldRelationHandler<CustomerSalesVO>().handler(customerSaleList, relations);
		
		return customerSaleList;
	}
	
	/**
	 * 客户批量分配
	 * @param orgIdStr
	 * @param cumIdStr
	 * @param ownerDeptIdStr
	 * @param ownerUserIdStr
	 */
	public void batchAllocation(String orgIdStr, String cumIdStr, String ownerDeptIdStr, String ownerUserIdStr){
		String[] cumIds = cumIdStr.split(",");
		Map<String, List<CustomerSalesDO>> result = getOrgSaleDOs(orgIdStr, cumIds, ownerDeptIdStr, ownerUserIdStr);
		List<CustomerSalesDO> addDOs = result.get("add");
		List<CustomerSalesDO> updateDOs = result.get("update");
		for(CustomerSalesDO add:addDOs){
			//判断客户是否停用
			CustomerVO cumVo = cumService.getDetail(add.getCumId());
			if(cumVo.getEnableState() == 2){
				continue;
			}
			
			this.saveVO(add);
		}
		for(CustomerSalesDO update:updateDOs){
			//判断客户是否停用
			CustomerVO cumVo = cumService.getDetail(update.getCumId());
			if(cumVo.getEnableState() == 2){
				continue;
			}
			
			this.updateVO(update);
		}
	}
	
	/**
	 * 处理公司客户批量分配
	 * @param orgIdStr
	 * @param cumIds
	 * @param ownerDeptIdStr
	 * @param ownerUserIdStr
	 * @return
	 */
	private Map<String, List<CustomerSalesDO>> getOrgSaleDOs(String orgIdStr, String[] cumIds, String ownerDeptIdStr, String ownerUserIdStr){
		Map<String, Object> param = new HashMap<>();
		param.put("cumIds",cumIds);
		//param.put("userId", ownerUserIdStr);
		List<CustomerSalesDO> sales = dao.selectVoList(CustomerSalesDO.class, "exsitSaleByUser", param);
		Map<String, CustomerSalesDO> saleInfos = new HashMap<String, CustomerSalesDO>();
		for(CustomerSalesDO sale:sales){
			saleInfos.put(sale.getCumId().toString(), sale);
		}
		Map<String, List<CustomerSalesDO>> result = new HashMap<String, List<CustomerSalesDO>>();
		List<CustomerSalesDO> addDOs = new ArrayList<CustomerSalesDO>();
		List<CustomerSalesDO> updateDOs = new ArrayList<CustomerSalesDO>();
		result.put("add", addDOs);
		result.put("update", updateDOs);
		for(String cum:cumIds){
			CustomerSalesDO salen = saleInfos.get(cum);
			if(null==salen){					//分配
				salen = new CustomerSalesDO();
				addDOs.add(salen);
			}else{								//变更
				//TODO 
				updateDOs.add(salen);
			}
			salen.setOrgId(new Long(orgIdStr));
			salen.setCumId(new Long(cum));
			salen.setOwnerDeptId(new Long(ownerDeptIdStr));
			salen.setOwnerUserId(new Long(ownerUserIdStr));
		}
		return result;
	}
	
}